package nina.yiyou.performance.s11collect.compute.score

import groovy.transform.PackageScope
import nina.yiyou.performance.s11collect.input.CollectFilledReader

import static java.util.stream.Collectors.groupingBy
import static java.util.stream.Collectors.toList

/**
 * 把评分细项按大类合并
 */
@PackageScope
class GroupScoreCombiner {

  interface Group {

    String evaluateeId()

    String evalType()

    String name()

    double score()
  }

  GroupScoreCombiner(List<CollectFilledReader.Eval> itemList) {
    _itemList = itemList
  }

  List<Group> combine() {
    if (_itemList.isEmpty()) {
      return []
    }

    return _itemList.stream()
        .collect(groupingBy { CollectFilledReader.Eval e -> e.group() })
        .values().stream()
        .map { makeGroup(it) }
        .collect(toList())
  }

  private Group makeGroup(List<CollectFilledReader.Eval> elemList) {
    def toNum = { v ->
      if (v instanceof Number) {
        return v.toDouble()
      }
      try {
        return Double.parseDouble(v.toString())
      } catch (ignored) {
        return 0.0d
      }
    }

    double score = elemList.stream()
        .mapToDouble { toNum.call(it.value()) }
        .sum()

    CollectFilledReader.Eval employeeInfo = elemList[0]
    return new Group() {
      @Override
      String evaluateeId() {
        return employeeInfo.evaluateeId()
      }

      @Override
      String evalType() {
        return employeeInfo.type()
      }

      @Override
      String name() {
        return employeeInfo.group()
      }

      @Override
      double score() {
        return score
      }

      @Override
      String toString() {
        def e = employeeInfo
        return "${e.evaluateeName()}<-${e.fillerName()}:[${e.type()}_${e.group()}(${score})]"
      }
    }
  }

  private final List<CollectFilledReader.Eval> _itemList
}
